package com.spring.hot;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Cizai
 * @since 2022/12/05 14:15
 **/
public class 组合总和 {

    List<List<Integer>> result = new ArrayList<>();
    ArrayList<Integer> list = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        backtrack(candidates,target,0);
        return result;
    }

    private void backtrack(int[] candidates, int target, int start) {
        if (sum == target){
            result.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (sum+candidates[i]>target) continue;
            sum+=candidates[i];
            list.add(candidates[i]);
            backtrack(candidates,target,i);
            sum-=candidates[i];
            list.remove(list.size()-1);
        }
    }
}
